package cn.jingyuan.bee.fastjson;

import cn.jingyuan.bee.enums.EnumInteger;
import cn.jingyuan.bee.enums.EnumString;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;


public class BeeSerializeConfig extends SerializeConfig {

    public static final SerializeConfig globalInstance = new BeeSerializeConfig();

    public static SerializeConfig getGlobalInstance() {
        return globalInstance;
    }

    @Override
    public ObjectSerializer getObjectWriter(Class<?> clazz) {
        ObjectSerializer serializer;

        if (clazz.isEnum()) {
            JSONType jsonType = clazz.getAnnotation(JSONType.class);
            if (null != jsonType) {
                try {
                    Class<?> aClass = jsonType.serializer();
                    serializer = (ObjectSerializer) aClass.newInstance();
                    return serializer;
                } catch (Throwable error) {
                    // skip
                }
            }

            if (EnumString.class.isAssignableFrom(clazz)) {
                serializer = EnumStringSerializer.instance;
                this.put(clazz, serializer);
                return serializer;
            }

            if (EnumInteger.class.isAssignableFrom(clazz)) {
                serializer = EnumIntegerSerializer.instance;
                this.put(clazz, serializer);
                return serializer;
            }
        }
        return super.getObjectWriter(clazz);
    }

}
